var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var session = require('express-session');
var swaggerInstall = require('./utils/swagger')
var { expressjwt: jwt } = require('express-jwt');
var {secretKey,unless,algorithms} = require('./token');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentsRouter = require('./routes/students');
var classesRouter = require('./routes/classes');
var totalsRouter = require('./routes/totals');
const history = require('connect-history-api-fallback');

var app = express();
app.use(history());
swaggerInstall(app);
require('./db.js');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json({limit:'50mb'}));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use(session({
//   secret:"lovo",
//   resave:false, // 强制保存session，默认为true，即使它没有变化，建议false
//   saveUninitialized:true // 强制将未初始化的session存储（当新建一个sesison，但未设定属性和值时处于未初始化状态）
// }));
// app.use(jwt({secret:secretKey,algorithms}).unless(unless));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/students', studentsRouter);
app.use('/classes', classesRouter);
app.use('/totals',totalsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  if(err.status != 401){
    console.log(err);
  }
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
